package com.zhx.util;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class EhcacheUtil {

    public static EhcacheUtil ME = EhcacheUtil.getInstance();

    private static final String path = "/ehcache-config.xml";

    private static CacheManager manager;

    private static EhcacheUtil ehCache;

    private EhcacheUtil(String path) {
        manager = CacheManager.create(getClass().getResource(path));
    }

    public static EhcacheUtil getInstance() {
        if (ehCache == null) {
            ehCache = new EhcacheUtil(path);
        }
        return ehCache;
    }

    public static void put(String cacheName, String key, Object value) {
        Cache cache = manager.getCache(cacheName);
        Element element = new Element(key, value);
        cache.put(element);
    }

    public static Object get(String cacheName, String key) {
        Cache cache = manager.getCache(cacheName);
        Element element = cache.get(key);
        return element == null ? null : element.getObjectValue();
    }

    public Cache get(String cacheName) {
        return manager.getCache(cacheName);
    }

    public static void remove(String cacheName, String key) {
        Cache cache = manager.getCache(cacheName);
        cache.remove(key);
    }

    public static void main(String[] args) {

        put("users", "hello-1", "hello-value-1");
        put("users", "hello-2", "hello-value-2");

        System.out.println("ֵ" + get("users", "hello-1"));
        System.out.println("ֵ" + get("users", "hello-2"));

    }

}
